package com.wx.md.socket;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.net.Socket;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class WebsocketHandler extends TextWebSocketHandler {
    public Map<String, WebSocketSession> webSessionMap = new HashMap<>();
    private MiniCapDataHandler miniCapDataHandler;
    Socket socketClient = null;

    @Override
    protected void handleTextMessage(WebSocketSession session,
                                     TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        //接收前台点击事件后调用进行点击处理
        String commandstr = message.getPayload();
        URI sn = session.getUri();

    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //建立websocket链接后直接开启minicap
        URI sn = session.getUri();
        System.out.println("sn" + sn);
        System.out.println("session" + session.getId());
        if(socketClient==null||socketClient.isClosed()){
            socketClient = new Socket("localhost", 1717);
        }
        webSessionMap.put(session.getId(), session);
        getMinicapData(webSessionMap, socketClient);
    }

    private void getMinicapData(Map<String, WebSocketSession>  sessions, Socket socketClient) {
        miniCapDataHandler = new MiniCapDataHandler();
        miniCapDataHandler.setRunning(true);
        miniCapDataHandler.RunImageBinaryFrameCollectorThread(socketClient);
        miniCapDataHandler.RunImageConverterThread(webSessionMap);

    }



    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        miniCapDataHandler.setRunning(false);
        socketClient.close();
        webSessionMap.remove(session.getId());
    }
}
